﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
using CoolCode.Caching;

namespace CoolCode.Web
{
    public class WebCacheStrategy :  ICache //ICacheStrategy
    {
        private static Cache cache;

        #region ICacheStrategy Members

        public WebCacheStrategy()
        {
            cache = System.Web.HttpContext.Current.Cache;
        }

        public void Insert(string key, object value)
        {
            cache.Insert(key, value);
        }

        public object Get(string key)
        {
            return cache.Get(key);
        }

        public void Remove(string key)
        {
            cache.Remove(key);
        }

        #endregion

        #region ICache Members

        public object this[string key]
        {
            get
            {
                return cache[key];
            }
            set
            {
                cache[key]= value ;
            }
        }

        //创建一个绝对过期策略：
        //Cache.Insert("Time", strTime, null, DateTime.Now.AddMinutes( 1 ), Cache.NoSlidingExpiration );
        //创建相对过期策略：
        //Cache.Insert("Time", strTime, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes( 1 ) );
        //设置缓存项的优先级：
        //Cache.Insert("Time", strTime, null,Cache.NoAbsoluteExpiration,Cache.NoSlidingExpiration,CacheItemPriority.High,null);
        public void Insert(string key, object value, ICacheDependency dependency)
        {
            if (dependency == null)
                cache.Insert(key, value);
            if (!string.IsNullOrEmpty(dependency.FileName) || dependency.Keys != null)
                cache.Insert(key, value, new CacheDependency(new string[] { dependency.FileName }, dependency.Keys));
            else if (dependency.Expiration > DateTime.Now)
                cache.Insert(key, value, null, dependency.Expiration, Cache.NoSlidingExpiration);
        }

        public void Insert(string key, object value, int seconds)
        {
            cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(seconds));
        }

        #endregion

        #region IEnumerable Members

        public System.Collections.IEnumerator GetEnumerator()
        {
            return cache.GetEnumerator();
        }

        #endregion
    }
}
